package com.iye.puretennis.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.domain.Gender;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.*;
import com.iye.puretennis.utils.ImageUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/7.
 */
public class ProfileActivity extends Activity implements View.OnClickListener,TabHostResultListener{

    private Spinner idolSpinner;
    private RadioGroup genderRadioGroup;
    private RadioButton femaleRadio;
    private RadioButton maleRadio;
    private ImageView uploadImageView;
    private PopupWindow popupWindow;

    private ArrayAdapter<Idol> adapter;
    private DBManager dbManager;

    private List<Idol> idols = new ArrayList<Idol>();
    private Profile profile;
    private UserToken token;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
        dbManager = new DBManager(this);
        token = dbManager.retrieveCurrentUser();

        idolSpinner = (Spinner) findViewById(R.id.spinner_idollist);
        genderRadioGroup = (RadioGroup) findViewById(R.id.profile_gender_group);
        femaleRadio = (RadioButton) findViewById(R.id.profile_gender_female);
        maleRadio = (RadioButton) findViewById(R.id.profile_gender_male);
        uploadImageView = (ImageView) findViewById(R.id.profile_image_view);

        uploadImageView.setOnClickListener(this);
        //render page
        new Thread(new Runnable() {
            @Override
            public void run() {
                profile = loadProfile(token.getGuid(),token.getToken());
                idols = loadIdols(token.getToken());
                runOnUiThread(uiProfileUpdate);
            }
        }).start();
    }


    private Runnable uiProfileUpdate = new Runnable() {
        @Override
        public void run() {
            if(profile != null){
                renderProfile(profile);
            }
        }
    };

    //update the check -  uncheck icon
    private void handleGenderIcon(RadioButton checked,RadioButton uncheck){
        Drawable radioChecked = getResources().getDrawable(R.drawable.gender_checked);
        radioChecked.setBounds(0,0,radioChecked.getMinimumWidth(),radioChecked.getMinimumHeight());
        Drawable radioUncheck = getResources().getDrawable(R.drawable.gender_uncheck);
        radioUncheck.setBounds(0,0,radioUncheck.getMinimumWidth(),radioUncheck.getMinimumHeight());

        checked.setCompoundDrawables(radioChecked,null,null,null);
        uncheck.setCompoundDrawables(radioUncheck,null,null,null);
    }

    private  void renderProfile(Profile profile){
        //nick name
        EditText nickNameView = (EditText) findViewById(R.id.nickname);
        nickNameView.setText(profile.getName());

        //add radio group checked change listener
        genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == femaleRadio.getId()){
                    handleGenderIcon(femaleRadio,maleRadio);
                }else{
                    handleGenderIcon(maleRadio,femaleRadio);
                }
            }
        });

        if(Gender.FEMALE.name().equals(profile.getGender())){
            genderRadioGroup.check(femaleRadio.getId());
            handleGenderIcon(femaleRadio,maleRadio);
        }else{
            genderRadioGroup.check(maleRadio.getId());
            handleGenderIcon(maleRadio,femaleRadio);
        }


        /************************* my idol *********************************/
        //第二步：为下拉列表定义一个适配器，这里就用到里前面定义的list。
        adapter = new ArrayAdapter<Idol>(this,android.R.layout.simple_spinner_item, idols);
        //第三步：为适配器设置下拉列表下拉时的菜单样式。
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        idolSpinner.setAdapter(adapter);
        //第五部，设置选中项
        int spinnerSelectedPosition = selectedSpinnerPosition(profile.getIdolGuid());
        idolSpinner.setSelection(spinnerSelectedPosition);

        idolSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            @SuppressWarnings("unchecked")
            public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
                /* 将mySpinner 显示*/
                Idol idol = (Idol) arg0.getSelectedItem();
                arg0.setVisibility(View.VISIBLE);
            }
            @SuppressWarnings("unchecked")
            public void onNothingSelected(AdapterView arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }

    private int selectedSpinnerPosition(String myIdolGuid) {
        for(int i= 0;i<idols.size();i++){
            if(idols.get(i).getGuid().equals(myIdolGuid)){
                return i;
            }
        }
        return 0;
    }

    /**
     * update the profile of the user
     * @param view
     */
    public void updateProfile(View view) {
        EditText nickNameTag = (EditText) findViewById(R.id.nickname);
        final String nickname = nickNameTag.getText().toString();
        RadioButton genderBtn = (RadioButton) findViewById(genderRadioGroup.getCheckedRadioButtonId());
        String gender = Gender.FEMALE.name();
        if(maleRadio.getId() == genderBtn.getId()){
            gender = Gender.MALE.name();
        }
        final Idol idol = (Idol) idolSpinner.getSelectedItem();
        final String finalGender = gender;
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject profileJsonObj = new JSONObject();
                try {
                    profileJsonObj.put("guid",token.getGuid());
                    profileJsonObj.put("nickname",nickname);
                    profileJsonObj.put("gender", finalGender);
                    profileJsonObj.put("idolGuid",idol.getGuid());
                    StringEntity paramEntity = new StringEntity(profileJsonObj.toString(),Constant.CHARSET_UTF8);
                    ServerAccessHelper.queryStringForPost(RemoteUrlCollections.PROFILE, token.getToken(), paramEntity);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**************************Remote server request part*********************************/
    private List<Idol> loadIdols(String access_token) {
        List<Idol> idols = new ArrayList<Idol>();
        String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.IDOLS,access_token);
        if(!Constant.RESPONSE_BADLY.equals(result)){
            try {
                JSONArray jsonArrays = new JSONArray(result);
                for (int i = 0; i < jsonArrays.length(); i++) {
                    JSONObject jsonObj = jsonArrays.getJSONObject(i);
                    String guid = jsonObj.getString("guid");
                    String name = jsonObj.getString("name");
                    idols.add(new Idol(guid, name));
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return idols;
    }

    private Profile loadProfile(String userGuid, String access_token) {
        String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.PROFILE + "/" + userGuid,access_token);
        if(!Constant.RESPONSE_BADLY.equals(result)) {
            try {
                JSONObject json = new JSONObject(result);
                String guid = json.getString("guid");
                String name = json.getString("nickname");
                String gender = json.getString("gender");
                String idolGuid = json.getString("idolGuid");
                return new Profile(guid, name, gender, idolGuid);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private void showPopUp() {
        popupWindow=new UploadImagePopupWindow(this, null);
        popupWindow.showAtLocation(findViewById(R.id.profile), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void onClick(View view) {
        int vid = view.getId();
        if(vid==uploadImageView.getId()){
            showPopUp();
        }

    }

    @Override
    public void onTabActivityResult(int requestCode, int resultCode, Intent data) {

        // 拍照
        if (requestCode == Config.PHOTOHRAPH) {
            //将保存在本地的图片取出并缩小后显示在界面上
            //Bitmap bitmap = BitmapFactory.decodeFile(filePath);
//            addPictureData(filePath);
            if (data != null) {
                // 得到图片的全路径
                replaceImage(data);

            }
        }
        // 读取相册缩放图片
        if (requestCode == Config.PHOTOZOOM) {
            if (data != null) {
                // 得到图片的全路径
                replaceImage(data);


            }
        }

    }

    private void replaceImage(Intent data) {
        Uri uri = data.getData();

        String originalPath= ImageUtils.getRealPathFromURI(this, uri);
        Bitmap bitmap = ImageUtils.decodeSampledBitmapFromResource(originalPath, 40, 40);
        int degree = ImageUtils.readPictureDegree(originalPath);
        bitmap = ImageUtils.rotateBitmap(bitmap, degree);

        final Bitmap compress = ImageUtils.compressImage(bitmap, 200);
        this.uploadImageView.setImageBitmap(compress);
    }


    /**********************************Inner class for response json string******************************************/

    private class Profile{
        private String guid;
        private String name;
        private String gender;
        private String idolGuid;

        private Profile(String guid, String name, String gender, String idolGuid) {
            this.guid = guid;
            this.name = name;
            this.gender = gender;
            this.idolGuid = idolGuid;
        }

        public Profile() {

        }

        public String getGuid() {
            return guid;
        }
        public String getName() {
            return name;
        }
        public String getGender() {
            return gender;
        }
        public String getIdolGuid() {
            return idolGuid;
        }
    }

    private class Idol{
        private String guid;
        private String name;

        public Idol(String guid, String name) {
            this.guid = guid;
            this.name = name;
        }
        public String toString(){
            return name;
        }
        public String getGuid() {
            return guid;
        }
        public String getName() {
            return name;
        }
    }

}